package com.asktgapp.user.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.asktgapp.JGTool.JGColor;
import com.asktgapp.JGTool.Utils;
import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.engineer.activity.QuestionActivity;
import com.asktgapp.eventbus.EngineerPassEvent;
import com.asktgapp.eventbus.HasNewEvent;
import com.asktgapp.hxsg.BiuEaseHelper;
import com.asktgapp.model.ChatRecordVO;
import com.asktgapp.modulebase.common.adapter.BaseAdapter;
import com.asktgapp.modulebase.common.adapter.BaseViewHolder;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.modulebase.common.util.Util;
import com.asktgapp.utils.ImageDisplayUtil;
import com.asktgapp.widget.RefreshRecyclerView;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.utils.EaseCommonUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * time:2018/2/1
 * Create By ZhaoKai
 * Email: dczk@foxmail.com
 * Description:
 */

public class ConsultItemFragment extends BaseFragment {
    private RefreshRecyclerView mRefreshRecyclerView;
    private BaseAdapter mBaseAdapter;
    private RecyclerView mRecyclerView;
    private int mPage = 1;
    private int type = 0;
    private Apiservice mApiservice;
    private TextView mNewMsg;
    private int mZXType;
    private LinearLayout noData;
    private List<ChatRecordVO.userListBean> mDatalist = new ArrayList<>();

    //0,1普通用户 2,3工程师
    public static ConsultItemFragment newInstance(int type) {
        ConsultItemFragment fragment = new ConsultItemFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        Log.i("type", "newInstance:type= " + type);
        fragment.setArguments(bundle);
        return fragment;
    }

    public void showNoData() {
        noData.setVisibility(View.VISIBLE);
        noData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadData();
            }
        });
        mRefreshRecyclerView.setVisibility(View.GONE);
    }

    public void hideNoData() {
        noData.setVisibility(View.GONE);
        mRefreshRecyclerView.setVisibility(View.VISIBLE);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_consult_item, container, false);
        EventBus.getDefault().register(this);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }

    @Override
    protected void initView(View rootView) {
        Bundle bundle = getArguments();
        type = bundle.getInt("type");
        Log.i("type", "getArguments:type= " + type);
        mApiservice = ApiUtil.getInstance().create();
        mRefreshRecyclerView = rootView.findViewById(R.id.recycle);
        mRecyclerView = mRefreshRecyclerView.getRecyclerView();
        mNewMsg = rootView.findViewById(R.id.tv_has_new_msg);
        noData = rootView.findViewById(R.id.ll_no);
        mRefreshRecyclerView.setLoadMoreAction(new RefreshRecyclerView.Action() {
            @Override
            public void onAction(int page) {
                mRefreshRecyclerView.endPage();
                loadData();

            }
        });

        mRefreshRecyclerView.setRefreshAction(new RefreshRecyclerView.Action() {
            @Override
            public void onAction(int page) {
                mRefreshRecyclerView.endPage();
                loadData();

            }
        });
        mBaseAdapter = new BaseAdapter(getActivity()) {
            @Override
            public BaseViewHolder getViewHolder(ViewGroup parent, int viewType) {

                //工程师和普通用户共用的当前咨询fragment
                BaseViewHolder holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_consult, parent, false), new BaseViewHolder.Callbacks() {
                    @Override
                    public void bind(BaseViewHolder holder, Object data) {
                        if (data instanceof ChatRecordVO.userListBean) {
                            ChatRecordVO.userListBean bean = (ChatRecordVO.userListBean) data;
                            ImageView imageView = holder.getView(R.id.iv_head_engineer);
                            TextView time = holder.getView(R.id.tvMsgTime);
                            TextView status = holder.getView(R.id.tvTime);
                            TextView lable = holder.getView(R.id.tv_lable);
                            TextView hasNewMsg = holder.getView(R.id.msgNumber);
                            if (type == 0 || type == 2) {
                                if (bean.getUnRead() > 0) {
                                    hasNewMsg.setVisibility(View.VISIBLE);
                                } else {
                                    hasNewMsg.setVisibility(View.GONE);
                                }
                            }
                            //TODO 获取图片，后台接口没有给出来
                            ImageDisplayUtil.loadCircleHeadImage(getActivity(), imageView, bean.getUser_pic());
                            if (type == 0 || type == 1) {
                                holder.setText(R.id.tv_name, Util.isEmpty(bean.getRealname()) ? bean.getUsername() : bean.getRealname());
                            } else {
                                holder.setText(R.id.tv_name, bean.getUsername());
                            }

                            //标签
                            if (!Util.isEmpty(bean.getLabel())) {
                                lable.setVisibility(View.VISIBLE);
                                String[] str = bean.getLabel().split(",");
                                lable.setText(str[0]);
                            } else {
                                lable.setVisibility(View.GONE);
                            }
                            String type = "";
                            if (bean.getType() == 0) {
                                type = "即时咨询 ";
                            } else if (bean.getType() == 1) {
                                type = getString(R.string.homePage_used_check);
                            } else if (bean.getType() == 2) {
                                type = getString(R.string.homePage_problem_check);
                            }
                            if (!Util.isEmpty(bean.getTime())) {
                                time.setText(bean.getTime() + " | " + type);
                            } else {
                                time.setText(type);
                            }
                            if (bean.getIs_end() == 0) {
                                if (!Util.isEmpty(bean.getLastContent())) {
                                    holder.setText(R.id.tv_content, bean.getLastContent());
                                    //// TODO: 2018/3/5 时间需要转换

                                    if (bean.isRepeat()) {
                                        status.setText("已回复");
                                        status.setTextColor(JGColor.ACCOUNT_RECORD_YELLOW);
                                    } else {
                                        status.setText("待回复");
                                        status.setTextColor(JGColor.ACCOUNT_RECORD_BLUE);
                                    }
                                } else {
                                    holder.setText(R.id.tv_content, "");
                                    time.setText(type);
                                    status.setText("");
                                }
                            } else {
                                status.setText("已结束");
                                status.setTextColor(JGColor.APP_TEXT_SECOND);
                                if (!Util.isEmpty(bean.getLastContent())) {
                                    holder.setText(R.id.tv_content, bean.getLastContent());
                                } else {
                                    holder.setText(R.id.tv_content, "");
                                }
                            }


                        }

                    }

                    @Override
                    public void onItemClick(View view, int position) {
                        //考虑 结束后看详情的情况
                        ChatRecordVO.userListBean bean = (ChatRecordVO.userListBean) mBaseAdapter.getData().get(position);
                        if (Util.isEmpty(bean.getHuanxin_id())) {
                            showTost("对方不在线", 1);
                            return;
                        }
                        if (type == 1 || type == 0) {//普通用户显示真实姓名
                            BiuEaseHelper
                                    .getInstance()
                                    .beginSingleChat(getActivity(), "", bean.getHuanxin_id()
                                            , Util.isEmpty(bean.getRealname()) ? bean.getUsername() : bean.getRealname()
                                            , bean.getUser_pic(), bean.getId() + ""
                                            , type, bean.getCid() + "", bean.getType());
                        } else {
                            BiuEaseHelper
                                    .getInstance()
                                    .beginSingleChat(getActivity(), "", bean.getHuanxin_id()
                                            , bean.getUsername()
                                            , bean.getUser_pic(), bean.getId() + ""
                                            , type, bean.getCid() + "", bean.getType());
                        }
                    }
                });
                return holder;
            }
        }

        ;
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        mRecyclerView.setAdapter(mBaseAdapter);

    }


    @Override
    public void loadData() {
        Log.i("type", "loadData:type= " + type);
        if (type == 1 || type == 0) {
            mNewMsg.setVisibility(View.GONE);
            getUserData();
        } else if (type == 2 || type == 3) {
            getEngineerData();

        }
    }

    @Override
    public void onResume() {
        super.onResume();
//        if (type == 0 || type == 2)
        if (PreferencesUtil.getBoolean(getActivity(), PreferencesUtil.KEY_IS_ENGINEER)) {
            if (type == 0) {
                type = 2;
            } else if (type == 1) {
                type = 3;
            }
        } else {
            if (type == 2) {
                type = 0;
            } else if (type == 3) {
                type = 1;
            }
        }
        loadData();
        if (type == 0 || type == 2) {
//            BiuEaseHelper.loginIn();
        }

    }

    private void getEngineerData() {
        HashMap params = new HashMap();
        params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        if (type == 3) {
            //历史咨询
            params.put("type", 1);
            isEnd = 1;
        } else {
            //当前咨询
            params.put("type", 0);
            isEnd = 0;
        }

        Call<ApiResponseBody<ChatRecordVO>> call = mApiservice.projecterIndex(params);
        call.enqueue(new Callback<ApiResponseBody<ChatRecordVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<ChatRecordVO>> call, Response<ApiResponseBody<ChatRecordVO>> response) {
                if (response.isSuccessful()) {
                    ChatRecordVO recordVO = response.body().getResult();
                    if (type == 2) {
                        if (recordVO.getHas_problem() == 1) {
                            mNewMsg.setVisibility(View.GONE);
                            mNewMsg.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    // TODO: 2018/3/5跳转到问答列表Question待解答
                                    Intent intent = new Intent(getActivity(), QuestionActivity.class);
                                    intent.putExtra("positon", 1);
                                    startActivity(intent);
                                }
                            });
                        } else {
                            mNewMsg.setVisibility(View.GONE);
                        }
                    } else {
                        mNewMsg.setVisibility(View.GONE);
                    }
                    mDatalist = recordVO.getUserList();
                    setUI(mDatalist);
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<ChatRecordVO>> call, Throwable t) {
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
//                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
//                    showSetNetworkSnackbar();
                } else {
//                    showTost(apiException.getMessage(), 0);
                }
            }
        });


    }

    private void setUI(List<ChatRecordVO.userListBean> list) {

        if (list.size() == 0) {
            showNoData();
            return;
        } else {
            hideNoData();
        }

//        List list = new ArrayList();//如果要剔除获取不到记录的对话则放开这行与①，注释掉②
        String mHXID = PreferencesUtil.getString(getActivity(), PreferencesUtil.KEY_HX_ID);
        EMClient.getInstance().chatManager().loadAllConversations();
        for (ChatRecordVO.userListBean bean : list) {
            EMConversation conversation = EMClient.getInstance().chatManager().getConversation(bean.getHuanxin_id(), EaseCommonUtils.getConversationType(EaseConstant.CHATTYPE_SINGLE), false);
            if (conversation != null) {
                List<EMMessage> msgs = conversation.getAllMessages();
                Collections.reverse(msgs);
                EMMessage last = null;

                for (int i = 0; i < msgs.size(); i++) {
                    EMMessage l = msgs.get(i);
                    if (l.getFrom().equals(mHXID) || l.getTo().equals(mHXID)) ;
                    last = l;
                    break;
                }
                if (last != null) {
                    if (last.isUnread()) {
                        bean.setUnRead(1);
                    } else {
                        bean.setUnRead(0);
                    }
                    bean.setUnRead(conversation.getUnreadMsgCount());
                    Log.i("EMConversation", last.toString());
                    if (last.getType() == EMMessage.Type.TXT) {
                        String s = last.getBody().toString().replace("txt:", "").replaceAll("\"", "");
                        bean.setLastContent(s);
                    } else if (last.getType() == EMMessage.Type.VOICE) {
                        bean.setLastContent("[语音]");
                    } else if (last.getType() == EMMessage.Type.IMAGE) {
                        bean.setLastContent("[图片]");
                    }
                    if (last.direct() == EMMessage.Direct.SEND) {
                        bean.setRepeat(false);
                    }
                    if (last.direct() == EMMessage.Direct.RECEIVE) {
                        bean.setRepeat(true);
                    }
                    Date date = new Date();
                    date.setTime(last.getMsgTime());
                    bean.setTime(Utils.getAskTime(date));
//                list.add(bean);//①
                } else {
                    Log.i("EMConversation", "null");
                }
            }
        }
        mBaseAdapter.setData(list);//②
//        mBaseAdapter.setData(recordVO.getUserList());//①

    }


    private void getUserData() {
        HashMap params = new HashMap();
        params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        if (type == 1) {
            //历史咨询
            params.put("type", 1);
            isEnd = 1;
        } else {
            //当前咨询
            params.put("type", 0);
            isEnd = 0;
        }
        mNewMsg.setVisibility(View.GONE);
        Call<ApiResponseBody<List<ChatRecordVO.userListBean>>> call = mApiservice.chatList(params);
        call.enqueue(new Callback<ApiResponseBody<List<ChatRecordVO.userListBean>>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<List<ChatRecordVO.userListBean>>> call, Response<ApiResponseBody<List<ChatRecordVO.userListBean>>> response) {
                if (response.isSuccessful()) {
//                    List<ChatRecordVO.userListBean>
                    mDatalist = response.body().getResult();
                    setUI(mDatalist);
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<List<ChatRecordVO.userListBean>>> call, Throwable t) {
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
//                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }

            }
        });

    }


    //    private void getHxRecord(String hxid) {
//
//    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFresh(EngineerPassEvent event) {
        if (event.getType()) {
            if (type == 0 || type == 2) {
//                setUI(mDatalist);
                loadData();
            }

        }

    }

    private int isEnd;

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }
}
